import { DependencyContainer, HttpError, toSuccess, useEntityManager, useRedis } from '@sker/core';
import { AutoUser, KsDevice } from '@sker/entities';
import { useData } from '@sker/runtime';
import dayjs from 'dayjs';
import { z } from 'zod';
import { Core, CoreDevice } from './core/core';
import * as helper from './kwai/kwaiHelper';
export function randomTime() {
    return new Promise<void>((resolve, reject) => {
        setTimeout(() => resolve(), Math.random() * 1000 * 5)
    })
}
export function getDefaultCount(type: string): number {
    switch (type) {
        case '口令':
            return 80
        case '粉丝包':
            return 2;
        case '快币':
            return 100;
        case '分享':
            return 2;
        case '穿云箭':
            return 200;
        default:
            return 1000;
    }
}
export default async (injector: DependencyContainer) => {
    const input = z.object({
        uuid: z.string(),
        pkg: z.optional(z.string()),
        score: z.optional(z.number())
    })
    const body = input.parse(useData())
    let code: string = `start`;
    const list = await useEntityManager(async m => {
        const device = await m.findOne(KsDevice, { where: { uuid: body.uuid } })
        if (!device) {
            throw new HttpError(`参数有误`)
        }
        if (!device.owner) {
            throw new HttpError(`参数有误`)
        }
        const user = await m.findOne(AutoUser, { where: { mobile: device.owner } })
        if (!user) throw new HttpError(`用户不存在或已删除`)
        const userSetting = user.setting;
        if (userSetting?.status === 'stop') {
            code = 'stop'
            return []
        }
        if (['17661930079', '15822888383', '13046915000', '13753012123', '13713555594', '13817148097'].includes(user.mobile)) {
            return []
        }
        const setting = device.setting || {};
        if (setting?.stopTime) {
            const stopTime = dayjs(setting.stopTime).toDate().getTime()
            const nowTime = dayjs().toDate().getTime()
            if (stopTime > nowTime) {
                code = 'stop'
                return []
            }
        }
        const hours = user.setting.hours || []
        const hour = new Date().getHours()
        const isWorkHour = hours.includes(hour)
        if (['18639118753'].includes(user.mobile)) {
            const red = await useRedis(0, async (r) => {
                return await helper.getUpdateRoomInfo(r, ['穿云箭', '口令', '快币'], body.uuid, { ...device.setting, mobile: user.mobile, isWorkHour, id: device.id })
            });
            if (red) return [red]
            return []
        }
        if (!hours.includes(hour)) {
            return []
        }
        // const red = await useRedis(0, async (r) => {
        //     return await helper.getUpdateRoomInfo(r, ['穿云箭', '口令', '快币'], body.uuid, { ...device.setting, mobile: user.mobile })
        // });
        // if (red) return [red]
        // return []
        const owner = device.owner;
        let uuid = device.uuid;
        if (setting.sn) {
            uuid = `${owner}_${setting.sn}`
        }
        let { minCount, minMoneyV, red_type_chuan_yun_jian, red_type_kou_ling, red_type_kuai_bi, red_type_all } = setting as {
            minCount: number, minMoneyV: number, type: string, currentType: string, red_type_chuan_yun_jian: boolean,
            red_type_kou_ling: boolean, red_type_kuai_bi: boolean, red_type_all: boolean,
        };
        minCount = minCount || 0;
        minMoneyV = minMoneyV || 0;
        let type = `穿云箭`;
        if (red_type_chuan_yun_jian) type = '穿云箭';
        if (red_type_kou_ling) type = '口令';
        if (red_type_kuai_bi) type = '快币';
        if (red_type_all) type = '快币,口令,穿云箭';
        // 获取房间信息
        let currentItem: any;
        await useRedis(7, async r => {
            const core = new Core(r, user);
            const coreDevice = new CoreDevice()
            coreDevice.owner = device.owner;
            coreDevice.uuid = uuid;
            coreDevice.score = body.score || 0;
            await core.updateDeviceScore(coreDevice)
            const reds = await core.getDeviceRed(type.split(','), device.owner, uuid, device.setting)
            if (reds && reds.length > 0) {
                currentItem = reds[0]
            }
        });
        if (currentItem) {
            if (body.pkg) {
                await useRedis(8, async r => {
                    const key = `red.${body.uuid}`
                    const value = await r.get(key)
                    if (value) {
                        const json = JSON.parse(value)
                        if (body.pkg === `com.smile.gifmaker`) {
                            await r.set(key, JSON.stringify({
                                ...json,
                                link: json.link + 1,
                                ksLink: json.ksLink + 1
                            }))
                        } else {
                            await r.set(key, JSON.stringify({
                                ...json,
                                link: json.link + 1,
                                jsLink: json.jsLink + 1
                            }))
                        }
                    }
                    const endDate = dayjs().endOf('day').toDate().getTime()
                    const expirationTime = Math.floor((endDate - new Date().getTime()) / 1000)
                    await r.expire(key, expirationTime);
                });
            }
        }
        if (currentItem) {
            return [currentItem]
        }
        return [];
    })
    return toSuccess(list, 0)
}
